package com.fansm.config;

import com.fansm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * SpringSecurity的配置文件
 * WebSecurityCofniguration中 @Bean注解 把 FilterChainProxy 注入到了容器中 而且名称为springSecurityFilterChain
 * 而 FilterChainProxy 对象是通过 WebSecurity 构建的
 */
//@Configuration
//@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)// 数据库认证
            .passwordEncoder(bCryptPasswordEncoder); // 设置加密处理的方式
//        auth.inMemoryAuthentication().withUser("root").password("123");
    }

    /**
     * 容器中注入 BCryptPasswordEncoder
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * HttpSecurity 相当于 SpringSecurity配置文件中 http 标签
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 配置需要放过的资源
                .antMatchers("/login.html","/css/**","/img/**")
                .permitAll()
//                .antMatchers("/**")
//                .hasAnyRole("USER")
                .anyRequest()
                .authenticated()
                .and()
                // 配置登录表单相关的信息
                .formLogin()
                // 指定自定义的登录页面
                .loginPage("/login.html")
                .loginProcessingUrl("/login") // 表单提交的登录地址
                .defaultSuccessUrl("/home.html")
                .permitAll()
                .and()
                .rememberMe() // 放开 记住我 的功能
                .tokenRepository(persistentTokenRepository) // 持久化
                .and().csrf().disable();


    }

    /**
     * 向Spring容器中注入 PersistentTokenRepository 对象
     * @param dataSource
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository(DataSource dataSource){
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = "admin";
        // 每次都会生成一个随机的salt，同一个明文加密多次编码得到的密文其实都不一样
        System.out.println(encoder.encode(password));
        System.out.println(encoder.encode(password));
        System.out.println(encoder.encode(password));
    }
}
